package com.example.eci_quartz.cloudcc.impl;

import com.example.eci_quartz.cloudcc.commcon.DataGroupUtil;
import com.example.eci_quartz.cloudcc.dao.DefaultConnectionFactory;
import com.example.eci_quartz.cloudcc.dao.baseDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.*;

/***
 *
 *标准工时
 */
public class StandardJobImpl extends baseDao {

	java.text.SimpleDateFormat sdf= new java.text.SimpleDateFormat("yyyyMMdd");
	java.text.SimpleDateFormat sdfY= new java.text.SimpleDateFormat("yyyy");
	java.text.SimpleDateFormat sdfM= new java.text.SimpleDateFormat("MMdd");
//	String url_str = "http://172.16.254.185:9003/distributor.action";
	String binding = InsertXMInfo();
	Connection conn = new DefaultConnectionFactory().getConnection();
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	AccountImpl  accImpl=new AccountImpl();

	@SuppressWarnings("rawtypes")
	List<Map> updatelist = new ArrayList<Map>();

	@SuppressWarnings("rawtypes")
	List<Map> insertlist = new ArrayList<Map>();

	/**
	 * T+1获取DBS系统中的标准工时
	 *
	 * @throws SQLException
	 * @throws ParseException
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String StandardJob() throws SQLException, ParseException {
		Calendar cal=Calendar.getInstance();
	    cal.set(Calendar.DATE,cal.get(Calendar.DATE));


		String info = "false";

		String orderinfo = "";//查询返回来的值
		String order_datas = "";//查询成功返回来的数据
		Map<String, Map> orderMap = new HashMap<String, Map>();// map<销售订单编号，销售订单对象值>

		//String sql= "select * from  dbo.CRM_STOCK where (CRM_STOCK.LastMaintain1 = '"+yearday+"' or CRM_STOCK.LastMaintain2 = '"+yearday+"' or CRM_STOCK.LastMaintain3 = '"+yearday+"' or CRM_STOCK.LastMaintain4 = '"+yearday+"' or CRM_STOCK.LastMaintain5 = '"+yearday+"' or CRM_STOCK.LastMaintain6 = '"+yearday+"' or CRM_STOCK.LastMaintain7 = '"+yearday+"' ) ";//查询DBS零件库存的视图
		String sql="select *  FROM LIBJ49FSMS.STDJOB  fetch first 5 rows only ";
		try {
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			Map<String,Map> rsMap=new HashMap<String,Map>();//map<零件号，零件数据>从DBS查询出来的
			String codes="";//标准工时编号数组
			if (rs != null) {
				while (rs.next()) {
					Map mapObj=new HashMap();
					//标准工时编号
					String code="";
					// Job Code
					String jobcode=(rs.getString("JBCD") == null ? "" : rs.getString("JBCD")+ "").trim();
					// Component code
					String ljdm=(rs.getString("CPTCD") == null ? "" : rs.getString("CPTCD")+ "").trim();
					// Serial No
					String xlh=(rs.getString("BEQMSN") == null ? "" : rs.getString("BEQMSN")+ "").trim();
					// Shop/Field Code
					String sf=(rs.getString("SHPFLD") == null ? "" : rs.getString("SHPFLD")+ "").trim();

					//组合唯一编码
					if((jobcode!=null&&!"".equals(jobcode))&&(ljdm!=null&&!"".equals(ljdm))
					   &&(xlh!=null&&!"".equals(xlh))&&(sf!=null&&!"".equals(sf))){
						  code=xlh+"_"+ljdm+"_"+jobcode+"_"+sf;
						  codes+="'"+code+"',";
						  mapObj.put("name",code);
						  mapObj.put("jobcode",jobcode);
						  mapObj.put("ljdm",ljdm);
						  mapObj.put("xlh",xlh);
						  mapObj.put("sf",sf);

						// Business Group
					    String businessgroup=(rs.getString("BGRP") == null ? "" : rs.getString("BGRP")+ "").trim();
						mapObj.put("businessgroup",businessgroup);

					    mapObj.put("StandardNo", (rs.getString("FRSDHR") == null ? "" : rs.getString("FRSDHR")+ "").trim());
						// Quantity code
						mapObj.put("quantitycode",(rs.getString("CPTQTY") == null ? "" : rs.getString("CPTQTY")+ "").trim());


						// Modifier code
						mapObj.put("modifiercode",(rs.getString("CPTMD3") == null ? "" : rs.getString("CPTMD3")+ "").trim());
						// Cab Type
						mapObj.put("cabtype",(rs.getString("CABTY1") == null ? "" : rs.getString("CABTY1")+ "").trim());
						// Work App1 Code
						mapObj.put("workapp",(rs.getString("LWKAPP") == null ? "" : rs.getString("LWKAPP")+ "").trim());

						// F/R Exchange
						mapObj.put("exchange",(rs.getString("XFREXN") == null ? "" : rs.getString("XFREXN")+ "").trim());

						// Model
						mapObj.put("model",(rs.getString("EQMFMD") == null ? "" : rs.getString("EQMFMD")+ "").trim());
						// Make
						mapObj.put("make",(rs.getString("EQMFCD") == null ? "" : rs.getString("EQMFCD")+ "").trim());

						// Market Store
						//mapObj.put("marketstore",(rs.getString("STN1") == null ? "" : rs.getString("STN1")+ "").trim());
						// Job Loc Code
						mapObj.put("jobloc",(rs.getString("JOBLOC") == null ? "" : rs.getString("JOBLOC")+ "").trim());

						//rsMap.put(code, mapObj);
					}
			}

			 // .println("DBS同步数据： "+StandardNoS.length());
			 //判断标准工时编号是否存在
		     if(codes!=null&&!"".equals(codes)){
					//查询系统中全部的标准工时
					String data_query = "serviceName=cqlQuery&objectApiName=standardjob&expressions=select l.id,l.name from standardjob l where l.name is not null and l.name in ("+codes.substring(0, codes.length()-1)+")  and l.is_deleted='0'&binding="
					+ binding;//查询标准工时信息
					//.println("data_query====="+data_query);
					orderinfo = operate(data_query);
					String returninfo = "[" + orderinfo + "]";// 手动转换成json格式，方便取值
					if (returninfo != "[]") {
						JSONArray brand_list = JSONArray.fromObject(returninfo);
						if (brand_list != null) {
							for (int j = 0; j < brand_list.size(); j++) {
								JSONObject brandInfo = (JSONObject) brand_list.get(j);
								String Result = brandInfo.get("result") == null ? ""
										: brandInfo.get("result") + "";// 获取返回值
								String date = brandInfo.get("data") == null ? ""
										: brandInfo.get("data") + "";// 获取返回值
								if ("true".equals(Result)) {
									order_datas = date;
								}
							}
						}
					}
					// 查询CRM系统中零件库存的信息并存入到map中
					if (order_datas != "[]") {
						JSONArray datas_list = JSONArray.fromObject(order_datas);
						if (datas_list != null) {
							for (int i = 0; i < datas_list.size(); i++) {
								JSONObject accObj = (JSONObject) datas_list.get(i);
								JSONObject order_newObj = new JSONObject();//新的json，只存id，编号
								//DBS系统中的零件号
							    String code= (accObj.get("name")==null? "" : accObj.get("name").toString()).trim();
							    if(code!=null&&!"".equals(code)){
							    	order_newObj.put("id", accObj.get("id"));
									order_newObj.put("code", code);
									orderMap.put(code,order_newObj);
							    }
							}
						}
					}

			  }
			//.println("orderMap==="+orderMap.size()+"orderinfo===="+orderinfo);
			//判断零件是新增还是更新
			if(rsMap.size()>0&&rsMap!=null){
			   for(String StandardNo:rsMap.keySet()){
				    Map ljObj=rsMap.get(StandardNo);//获取DBS中的客户数据
				   if(orderMap.size()>0&&orderMap!=null){
					   if (orderMap.containsKey(StandardNo)) {// 更新标准工时
							updatelist.add(ljObj);
						} else {// 新建标准工时
							insertlist.add(ljObj);
						 }
					 }else{
						 insertlist.add(ljObj);
					 }
				}
			}
			//插入新的标准工时
			if (insertlist!=null&&insertlist.size() > 0) {
				Map<Integer,List> map = DataGroupUtil.dataGroup(insertlist); //用map存起来新的分组后数据,每100条一组
				if(map.size()>0){
					for(Integer m:map.keySet()){
						List amList=map.get(m);
						JSONArray jsonArrayInsert = JSONArray.fromObject(amList);
						String jsonstr=jsonArrayInsert.toString();
						jsonstr = java.net.URLEncoder.encode(jsonstr, "UTF-8");
						String data_insert = "serviceName=insertLt&objectApiName=standardjob&data="+jsonstr+"&binding="
					+ binding;//insertLt批量插入，不走触发器
			            operate(data_insert);//执行CRM系统插入操作insert
					    info="insert_success";
					}
				}
			}
			//更新系统中的标准工时
			if (updatelist!=null&&updatelist.size() > 0) {
				Map<Integer,List> map = DataGroupUtil.dataGroup(updatelist);
				if(map.size()>0){
					for(Integer m:map.keySet()){
						List amList=map.get(m);
						JSONArray jsonArrayUpdate = JSONArray.fromObject(amList);
						String jsonstr_update=jsonArrayUpdate.toString();
						jsonstr_update = java.net.URLEncoder.encode(jsonstr_update, "UTF-8");
						String data_update = "serviceName=updateLt&objectApiName=standardjob&data="+jsonstr_update+"&binding=" + binding;//updateLt批量更新，不走触发器
			            operate(data_update);//执行CRM更新操作update
			            info="update_success";
					}
				}
			}
		}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
				if (conn != null) {
					conn.close();
					conn = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return info;
	}

}
